package com.itcast.springboot.config;

import com.itcast.springboot.bean.Admin;
import com.itcast.springboot.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    AdminService adminService;

//    //授权
//    @Override
//    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("执行了授权命令");
//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
////        info.addStringPermission("user:add");
//
//        //拿到当前登录的这个对象
//        Subject subject = SecurityUtils.getSubject();
//        //取出在认证请求中SimpleAuthenticationInfo(user, user.getPwd(), "")
//        // 传入的user
//        User currentUser = (User) subject.getPrincipal();   //拿到user对象
//
//        //设置当前用户的权限
//        if(currentUser.getPerms() != null){
//            info.addStringPermission(currentUser.getPerms());
//        }
//        return info;
//    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证命令");
        //得到前端输入的用户名、密码
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //看是否能通过用户名从数据库中取出用户，不能则证明不存在
        Admin admin = adminService.getAdminByAcc(userToken.getUsername());
//        User user = userService.getUserByName(userToken.getUsername());
        if (admin == null) {
            return null;        //抛出UnknownAccountException异常
        }

        //密码错误，shiro做
        return new SimpleAuthenticationInfo(admin, admin.getPassword(), "");
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
